package com.brrbaii.config;

import com.brrbaii.Exception.BusinessException;
import com.brrbaii.common.ErrorCode;
import com.brrbaii.model.entity.User;
import com.brrbaii.utils.UserHolder;
import org.springframework.lang.Nullable;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import static com.brrbaii.common.StrConstants.USER_LOGIN_STATE;

public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Object attribute = request.getSession().getAttribute(USER_LOGIN_STATE);
        if(attribute == null){
            throw new BusinessException(ErrorCode.NOT_LOGIN,"请先登录用户");
        }
        User userLogin = (User) attribute;
        UserHolder.saveUser(userLogin);
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception {
        UserHolder.removeUser();

    }


}
